import { login,logout,getMenuList,loginByWechat,getALLDeviceList,getToken} from '@/API/user';
import { encryption } from '@/utils/utils';
import qs from 'qs';
import {getSession,setSession} from '@/API/storage';
import Router from '@/router/index';
import {sendSock,initWebSocket} from "@/utils/socket";

const state = {
  token: getSession('token') || '',  //token
  userinfo: getSession('userinfo') ||  '', //用户信息
  menuList: getSession('menuList') || [] ,//菜单列表
  projects:getSession('projects') || [],
  projectInfo:getSession('projectInfo') || '',//项目信息
  deviceAll:getSession('deviceAll') || [],
  uavStatus:getSession('uavStatus') || {},
};
const mutations = {
  SET_TOKEN: (state:any, token:string) => {
    state.token = token;
    setSession('token',token)
  },
  SET_USERINFO: (state:any, userinfo:object) => {
    state.userinfo = userinfo;
    setSession('userinfo',userinfo)
  },
  SET_MENULIST: (state:any, menuList:any) => {
    state.menuList = menuList;
    setSession('menuList',menuList)
  },
  SET_PROJECTINFO: (state:any, projectInfo:any) => {
    state.projectInfo = projectInfo;
    setSession('projectInfo',projectInfo)
  },
  SET_PROJECTS: (state:any, projects:object) => {
    state.projects = projects;
    setSession('projects',projects)
  },
  SET_ALLDEVIRE: (state:any, deviceAll:any) => {
    state.deviceAll = deviceAll;
    setSession('deviceAll',deviceAll)
  },
  SET_DEVICESTATUS: (state:any, obj:any) => {
    state.uavStatus = obj;
    setSession('uavStatus',obj)
  }
};
const actions = {
  // 用户登录
  login({commit},userInfo:object) {
    const user = encryption({
      data: userInfo,
      key: 'pigxpigxpigxpigx',
      param: ['password']
    })
    let data = qs.stringify({'username': user.username, 'password': user.password})
    let params = {
      randomStr:"blockPuzzle",
      grant_type:'password'
    }
    return new Promise((resolve, reject) => {
      login(params,data).then(res => {
        commit('SET_TOKEN', res.access_token);
        commit('SET_USERINFO', res.user_info);
        // 开始订阅 初始化socket
        // initWebSocket('wss://m2m.gizwits.com:8880/ws/app/v1',function(flag){
        //   if(flag){
        //       getToken().then(res => {
        //           let data = {
        //               cmd: "login_req",
        //               data: {
        //                   appid: "d8fa29e480f04baaad84c9006f089eb9",
        //                   uid: "b1655f9008874ea98786213efe54690d",
        //                   token: res.data,
        //                   p0_type: "attrs_v4",
        //                   heartbeat_interval: 6000,
        //                   auto_subscribe: false
        //               }
        //           }
        //           sendSock(data,function(e){
        //               if(e.data.success){
        //                   console.log('登录成功')
        //               }else{
        //                   console.log('登录失败 ',e)
        //               }
        //           })
        //       })
        //   }
        // })
        resolve(res);
      }).catch((error)=>{reject(error);})
    })
  },
  //微信登录
  loginByWechat({commit},code:string | number){
    return new Promise((resolve, reject) => {
      loginByWechat(code).then(resoult => {
        if(resoult.code == 0){
          let res = resoult.data
          commit('SET_TOKEN', res.access_token);
          commit('SET_USERINFO', res.user_info);
          resolve(res);
        }else{
          reject("当前登陆用户未绑定项目,请检查")
        }
      }).catch((error)=>{reject(error);})
    })
  },
  //获取项目菜单列表
  getMenuList({commit,state}){
    return new Promise<void>((resolve, reject) => {
      getMenuList({
        projectId:state.projectInfo.deptId,
        tenantId:1
      }).then(res => {
        let menus = []
        res.data.map(item => {
          menus.push(item.code)
        })
        commit('SET_MENULIST', menus)
        resolve()
      }).catch((error)=>{reject(error);})
    })
  },
  // 获取全部设备
  getALLDeviceList({commit,state}){
    return new Promise<void>((resolve, reject) => {
      getALLDeviceList().then(res => {
        commit('SET_ALLDEVIRE', res.data.data)
        resolve()
      }).catch((error)=>{reject(error);})
    })
  },
  //退出
  logout({commit}){
    return new Promise((resolve, reject) => {
      logout().then(res => {
        commit('SET_TOKEN', '');
        commit('SET_USERINFO', null);
        Router.push({path:'/login'})
        resolve(res);
      }).catch((error)=>{reject(error);})
    })
  },
// UAV
  getUavStatus({commit},obj){
    return new Promise((resolve, reject) => {
        commit('SET_DEVICESTATUS',obj)
        resolve(obj);
      }).catch((error)=>{reject(error);})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
